"""
接口自动化相关数据模型
"""

from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey, JSON, Boolean, Float
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from ..core.database import Base


class ApiInterface(Base):
    """API接口模型"""
    __tablename__ = "api_interfaces"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(200), nullable=False, index=True)  # 接口名称
    description = Column(Text)  # 接口描述
    method = Column(String(10), nullable=False)  # HTTP方法: GET, POST, PUT, DELETE等
    url = Column(String(500), nullable=False)  # 接口URL
    headers = Column(JSON)  # 请求头，存储为JSON
    query_params = Column(JSON)  # 查询参数，存储为JSON
    body_type = Column(String(20), default="json")  # 请求体类型: json, form, raw, xml等
    body_content = Column(Text)  # 请求体内容
    
    # 认证相关
    auth_type = Column(String(20))  # 认证类型: none, basic, bearer, api_key等
    auth_config = Column(JSON)  # 认证配置
    
    # 状态和分类
    status = Column(String(20), default="active")  # active, inactive, deprecated
    category = Column(String(100))  # 接口分类
    tags = Column(JSON)  # 标签数组
    
    # 外键
    created_by = Column(Integer, ForeignKey("users.id"))
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关系
    creator = relationship("User")
    parameters = relationship("ApiParameter", back_populates="interface", cascade="all, delete-orphan")
    assertions = relationship("ApiAssertion", back_populates="interface", cascade="all, delete-orphan")
    flow_nodes = relationship("FlowNode", back_populates="interface")


class ApiParameter(Base):
    """API参数模型"""
    __tablename__ = "api_parameters"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), nullable=False)  # 参数名
    description = Column(Text)  # 参数描述
    param_type = Column(String(20), nullable=False)  # 参数类型: header, query, body, path
    data_type = Column(String(20), default="string")  # 数据类型: string, integer, boolean, array, object
    is_required = Column(Boolean, default=False)  # 是否必需
    default_value = Column(Text)  # 默认值
    example_value = Column(Text)  # 示例值
    validation_rules = Column(JSON)  # 验证规则
    
    # 参数来源（用于跨接口调用）
    source_type = Column(String(20), default="static")  # static, variable, response, env
    source_config = Column(JSON)  # 来源配置
    
    # 外键
    interface_id = Column(Integer, ForeignKey("api_interfaces.id"), nullable=False)
    created_by = Column(Integer, ForeignKey("users.id"))
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关系
    interface = relationship("ApiInterface", back_populates="parameters")
    creator = relationship("User")


class ApiAssertion(Base):
    """API断言模型"""
    __tablename__ = "api_assertions"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(200), nullable=False)  # 断言名称
    description = Column(Text)  # 断言描述
    assertion_type = Column(String(50), nullable=False)  # 断言类型: status_code, response_time, json_path, header, body_contains等
    target_path = Column(String(500))  # 目标路径（如JSONPath）
    operator = Column(String(20), nullable=False)  # 操作符: equals, not_equals, contains, greater_than等
    expected_value = Column(Text)  # 期望值
    is_enabled = Column(Boolean, default=True)  # 是否启用
    
    # 外键
    interface_id = Column(Integer, ForeignKey("api_interfaces.id"), nullable=False)
    created_by = Column(Integer, ForeignKey("users.id"))
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关系
    interface = relationship("ApiInterface", back_populates="assertions")
    creator = relationship("User")


class TestScenario(Base):
    """测试场景模型"""
    __tablename__ = "test_scenarios"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(200), nullable=False, index=True)  # 场景名称
    description = Column(Text)  # 场景描述
    status = Column(String(20), default="draft")  # draft, ready, running, completed, failed
    
    # 场景配置
    timeout = Column(Integer, default=30)  # 超时时间（秒）
    retry_count = Column(Integer, default=0)  # 重试次数
    parallel_execution = Column(Boolean, default=False)  # 是否并行执行
    
    # 环境变量
    environment_variables = Column(JSON)  # 环境变量
    
    # 外键
    created_by = Column(Integer, ForeignKey("users.id"))
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关系
    creator = relationship("User")
    flow_nodes = relationship("FlowNode", back_populates="scenario", cascade="all, delete-orphan")
    flow_connections = relationship("FlowConnection", back_populates="scenario", cascade="all, delete-orphan")
    executions = relationship("ScenarioExecution", back_populates="scenario")


class FlowNode(Base):
    """流程图节点模型"""
    __tablename__ = "flow_nodes"

    id = Column(Integer, primary_key=True, index=True)
    node_id = Column(String(50), nullable=False)  # 前端生成的唯一节点ID
    name = Column(String(200), nullable=False)  # 节点名称
    description = Column(Text)  # 节点描述
    node_type = Column(String(20), nullable=False)  # 节点类型: start, end, api_call, condition, loop
    
    # 节点位置
    position_x = Column(Float, default=0)  # X坐标
    position_y = Column(Float, default=0)  # Y坐标
    
    # 节点配置（根据类型存储不同的配置）
    node_config = Column(JSON)  # 节点配置数据
    
    # 状态配置
    is_enabled = Column(Boolean, default=True)  # 是否启用
    continue_on_failure = Column(Boolean, default=False)  # 失败时是否继续
    
    # 外键
    scenario_id = Column(Integer, ForeignKey("test_scenarios.id"), nullable=False)
    interface_id = Column(Integer, ForeignKey("api_interfaces.id"))  # 对于api_call类型的节点
    created_by = Column(Integer, ForeignKey("users.id"))
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关系
    scenario = relationship("TestScenario", back_populates="flow_nodes")
    interface = relationship("ApiInterface", back_populates="flow_nodes")
    creator = relationship("User")
    outgoing_connections = relationship("FlowConnection", foreign_keys="FlowConnection.source_node_id", back_populates="source_node", cascade="all, delete-orphan")
    incoming_connections = relationship("FlowConnection", foreign_keys="FlowConnection.target_node_id", back_populates="target_node", cascade="all, delete-orphan")


class FlowConnection(Base):
    """流程图连接模型"""
    __tablename__ = "flow_connections"

    id = Column(Integer, primary_key=True, index=True)
    connection_id = Column(String(50), nullable=False)  # 前端生成的唯一连接ID
    name = Column(String(200))  # 连接名称（可选）
    
    # 连接的源节点和目标节点
    source_node_id = Column(Integer, ForeignKey("flow_nodes.id"), nullable=False)
    target_node_id = Column(Integer, ForeignKey("flow_nodes.id"), nullable=False)
    
    # 连接条件配置（用于条件分支）
    condition_config = Column(JSON)  # 条件表达式和配置
    
    # 连接类型和属性
    connection_type = Column(String(20), default="default")  # default, success, failure, condition
    is_enabled = Column(Boolean, default=True)  # 是否启用
    
    # 外键
    scenario_id = Column(Integer, ForeignKey("test_scenarios.id"), nullable=False)
    created_by = Column(Integer, ForeignKey("users.id"))
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关系
    scenario = relationship("TestScenario", back_populates="flow_connections")
    creator = relationship("User")
    source_node = relationship("FlowNode", foreign_keys=[source_node_id], back_populates="outgoing_connections")
    target_node = relationship("FlowNode", foreign_keys=[target_node_id], back_populates="incoming_connections")


class ScenarioExecution(Base):
    """场景执行记录模型"""
    __tablename__ = "scenario_executions"

    id = Column(Integer, primary_key=True, index=True)
    execution_id = Column(String(50), nullable=False, index=True)  # 执行ID
    status = Column(String(20), nullable=False)  # pending, running, completed, failed, cancelled
    
    # 执行统计
    total_steps = Column(Integer, default=0)  # 总步骤数
    passed_steps = Column(Integer, default=0)  # 通过步骤数
    failed_steps = Column(Integer, default=0)  # 失败步骤数
    skipped_steps = Column(Integer, default=0)  # 跳过步骤数
    
    # 执行时间
    start_time = Column(DateTime(timezone=True))
    end_time = Column(DateTime(timezone=True))
    duration = Column(Float)  # 执行时长（秒）
    
    # 结果
    result_summary = Column(Text)  # 结果摘要
    error_message = Column(Text)  # 错误信息
    execution_log = Column(Text)  # 执行日志
    
    # 外键
    scenario_id = Column(Integer, ForeignKey("test_scenarios.id"), nullable=False)
    executor_id = Column(Integer, ForeignKey("users.id"))
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    
    # 关系
    scenario = relationship("TestScenario", back_populates="executions")
    executor = relationship("User")
    step_results = relationship("StepExecutionResult", back_populates="execution", cascade="all, delete-orphan")


class StepExecutionResult(Base):
    """步骤执行结果模型"""
    __tablename__ = "step_execution_results"

    id = Column(Integer, primary_key=True, index=True)
    step_name = Column(String(200), nullable=False)  # 步骤名称
    step_order = Column(Integer, nullable=False)  # 步骤顺序
    status = Column(String(20), nullable=False)  # passed, failed, skipped, error
    
    # 请求信息
    request_url = Column(String(500))
    request_method = Column(String(10))
    request_headers = Column(JSON)
    request_body = Column(Text)
    
    # 响应信息
    response_status_code = Column(Integer)
    response_headers = Column(JSON)
    response_body = Column(Text)
    response_time = Column(Float)  # 响应时间（毫秒）
    
    # 断言结果
    assertion_results = Column(JSON)  # 断言结果数组
    
    # 变量提取结果
    extracted_variables = Column(JSON)  # 提取的变量
    
    # 错误信息
    error_message = Column(Text)
    error_details = Column(Text)
    
    # 时间戳
    executed_at = Column(DateTime(timezone=True), server_default=func.now())
    
    # 外键
    execution_id = Column(Integer, ForeignKey("scenario_executions.id"), nullable=False)
    
    # 关系
    execution = relationship("ScenarioExecution", back_populates="step_results")


class EnvironmentConfig(Base):
    """环境配置模型"""
    __tablename__ = "environment_configs"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), nullable=False, index=True)  # 环境名称
    description = Column(Text)  # 环境描述
    base_url = Column(String(500))  # 基础URL
    variables = Column(JSON)  # 环境变量
    headers = Column(JSON)  # 全局请求头
    is_default = Column(Boolean, default=False)  # 是否为默认环境
    is_active = Column(Boolean, default=True)  # 是否激活
    
    # 外键
    created_by = Column(Integer, ForeignKey("users.id"))
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关系
    creator = relationship("User")